<template>
  <div class="jobs-management">
    <div class="search-container">
      <el-input
        v-model="searchQuery"
        placeholder="搜索职位标题/公司名称"
        class="search-input"
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="showAddDialog">新增职位</el-button>
    </div>
    <el-table :data="filteredJobs" style="margin-top:20px;">
      <el-table-column prop="job_id" label="ID" width="60" />
      <el-table-column prop="job_title" label="职位标题" />
      <el-table-column prop="company_name" label="公司" />
      <el-table-column prop="location" label="地点" />
      <el-table-column prop="is_open" label="开启" :formatter="formatOpen" />
      <el-table-column prop="post_date" label="发布日期" />
      <el-table-column prop="expiration_date" label="过期时间" />
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="editJob(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="deleteJob(row.job_id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="formData" label-width="120px">
        <el-form-item label="职位标题"><el-input v-model="formData.job_title" /></el-form-item>
        <el-form-item label="公司名称"><el-input v-model="formData.company_name" /></el-form-item>
        <el-form-item label="地点"><el-input v-model="formData.location" /></el-form-item>
        <el-form-item label="薪资范围"><el-input v-model="formData.salary_range" /></el-form-item>
        <el-form-item label="描述"><el-input type="textarea" v-model="formData.job_description" /></el-form-item>
        <el-form-item label="要求"><el-input type="textarea" v-model="formData.requirements" /></el-form-item>
        <el-form-item label="过期时间"><el-date-picker v-model="formData.expiration_date" type="datetime" placeholder="选择日期时间" /></el-form-item>
        <el-form-item label="开启"><el-switch v-model="formData.is_open" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveJob">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useAuthStore } from '../store/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

const auth = useAuthStore()
const jobs = ref([])
const searchQuery = ref('')
const dialogVisible = ref(false)
const isEditing = ref(false)
const dialogTitle = ref('')
const formData = reactive({
  job_id: null,
  job_title: '',
  company_name: '',
  location: '',
  salary_range: '',
  job_description: '',
  requirements: '',
  expiration_date: null,
  is_open: true,
  poster_id: auth.userId
})

// 添加过滤后的职位列表计算属性
const filteredJobs = computed(() => {
  if (!searchQuery.value) return jobs.value
  const query = searchQuery.value.toLowerCase()
  return jobs.value.filter(job => 
    job.job_title.toLowerCase().includes(query) ||
    job.company_name.toLowerCase().includes(query)
  )
})

// 添加搜索处理方法
const handleSearch = () => {
  // 搜索逻辑已通过计算属性实现
}

const fetchJobs = async () => {
  try {
    const token = auth.token
    const res = await fetch(`http://127.0.0.1:8000/api/job-postings`, {
      headers: { 'Authorization': `Bearer ${encodeURIComponent(token)}` }
    })
    if (!res.ok) throw new Error(await res.text())
    jobs.value = await res.json()
  } catch (err) {
    ElMessage.error('获取职位列表失败: ' + err.message)
  }
}

const showAddDialog = () => {
  isEditing.value = false
  dialogTitle.value = '新增职位'
  Object.assign(formData, { job_id: null, job_title: '', company_name: '', location: '', salary_range: '', job_description: '', requirements: '', expiration_date: null, is_open: true, poster_id: auth.userId })
  dialogVisible.value = true
}

const editJob = (job) => {
  isEditing.value = true
  dialogTitle.value = '编辑职位'
  Object.assign(formData, { job_id: job.job_id, job_title: job.job_title, company_name: job.company_name, location: job.location, salary_range: job.salary_range, job_description: job.job_description, requirements: job.requirements, expiration_date: job.expiration_date, is_open: job.is_open, poster_id: auth.userId })
  dialogVisible.value = true
}

const saveJob = async () => {
  try {
    if (!formData.job_title || !formData.company_name || !formData.location) {
      ElMessage.warning('请填写完整信息')
      return
    }
    const token = auth.token
    let res
    const payload = {
      job_title: formData.job_title,
      company_name: formData.company_name,
      location: formData.location,
      salary_range: formData.salary_range,
      job_description: formData.job_description,
      requirements: formData.requirements,
      expiration_date: formData.expiration_date,
      is_open: formData.is_open,
      poster_id: formData.poster_id
    }
    if (isEditing.value) {
      res = await fetch(`http://127.0.0.1:8000/api/job-postings/${formData.job_id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${encodeURIComponent(token)}` },
        body: JSON.stringify(payload)
      })
    } else {
      res = await fetch(`http://127.0.0.1:8000/api/job-postings`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${encodeURIComponent(token)}` },
        body: JSON.stringify(payload)
      })
    }
    const data = await res.json()
    if (!res.ok) throw new Error(data.detail || '操作失败')
    ElMessage.success('保存成功')
    dialogVisible.value = false
    fetchJobs()
  } catch (err) {
    ElMessage.error(err.message)
  }
}

const deleteJob = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除该职位吗？', '提示', { type: 'warning' })
    const token = auth.token
    const res = await fetch(`http://127.0.0.1:8000/api/job-postings/${id}?user_id=${auth.userId}`, {
      method: 'DELETE',
      headers: { 'Authorization': `Bearer ${encodeURIComponent(token)}` }
    })
    if (!res.ok) throw new Error(await res.text())
    ElMessage.success('删除成功')
    fetchJobs()
  } catch (err) {
    if (err !== 'cancel') ElMessage.error(err.message || '删除失败')
  }
}

const formatOpen = (row) => row.is_open ? '是' : '否'

onMounted(fetchJobs)
</script>

<style scoped>
.jobs-management {
  padding: 20px;
}
.search-container {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}
.search-input {
  width: 300px;
}
</style> 